package com.kly.cashmall.widget.picker;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;

/**
 * @author
 * @date 2017/6/19
 */
public class PickFileUtil {

  private static String getCacheDir(Context context) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      File baseFile = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
      if (baseFile.exists() || baseFile.mkdirs()) {
        return baseFile.getAbsolutePath();
      } else {
        return context.getCacheDir().getAbsolutePath();
      }
    } else {
      return context.getCacheDir().getAbsolutePath();
    }
  }

  public static Uri getCameraUri(Context context) {
    File pickDir = new File(getCacheDir(context), "pickDir");
    File mediaFile;
    if (pickDir.exists() || pickDir.mkdirs()) {
      mediaFile = new File(pickDir.getPath(), "IMG_" + System.currentTimeMillis() + ".jpg");
    } else {
      mediaFile = new File(getCacheDir(context), "IMG_" + System.currentTimeMillis() + ".jpg");
    }
    if (!mediaFile.exists()) {
      try {
        mediaFile.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (Build.VERSION.SDK_INT >= 24) {
      return FileProvider.getUriForFile(context, ImagePickUtil.getAuthorities(context), mediaFile);
    } else {
      return Uri.fromFile(mediaFile);
    }
  }

  public static String getTempDir(Context context) {
    File pickDir = new File(getCacheDir(context), ".tempDir");
    if (pickDir.exists() || pickDir.mkdirs()) {
      return pickDir.getPath();
    } else {
      return getCacheDir(context);
    }
  }

  public static Uri getGalleyTempUri(Context context) {
    File mediaFile = new File(getTempDir(context), "IMG_" + System.currentTimeMillis() + ".jpg");
    return Uri.fromFile(mediaFile);
  }
}
